package YZ.Students.Mier.controller.web;

import YZ.Students.Mier.Service.ICommentService;
import YZ.Students.Mier.Service.IInvitataionService;
import YZ.Students.Mier.Service.UserService;
import YZ.Students.Mier.Service.impl.CommentServiceImpl;
import YZ.Students.Mier.Service.impl.InvitataionServiceImpl;
import YZ.Students.Mier.Service.impl.UserServiceImpl;
import YZ.Students.Mier.controller.BaseServlet;
import YZ.Students.Mier.entity.InvitataionEntity;
import YZ.Students.Mier.entity.UserEntity;
import YZ.Students.Mier.vo.CommentVo;
import com.alibaba.fastjson.JSON;
import javax.servlet.annotation.WebServlet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@WebServlet("/invitataionServlet/*")
public class InvitataionServlet extends BaseServlet {

    private IInvitataionService invitataionService = new InvitataionServiceImpl();

    private UserService userService = new UserServiceImpl();

    private ICommentService commentService = new CommentServiceImpl();


    public String publish() throws Exception {

        // 1.获取登录用户
        UserEntity loginUser = (UserEntity) req.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            return outJson(100, "登录超时，请先登录");
        }

        // 2.获取前端传递的数据
        String s = req.getReader().readLine();
        InvitataionEntity invitataionEntity = JSON.parseObject(s, InvitataionEntity.class);

        // 3.封装用户
        invitataionEntity.setUserId(loginUser.getId());
        boolean save = invitataionService.save(invitataionEntity);

        return outJson(save);
    }

    public void info() throws Exception {
        String id = req.getParameter("id");
        // 1.查询帖子
        InvitataionEntity invitataionEntity = invitataionService.byId(Integer.parseInt(id));
        // 2.查询作者
        Integer userId = invitataionEntity.getUserId();
        UserEntity userEntity = userService.byId(userId);
        // 3.查询帖子的评论
        List<CommentVo> commentEntityList = commentService.commentListByInvitataionId(invitataionEntity.getId());
        // 4.把帖子的数据和作者的数据放到map中
        Map<String, Object> map = new HashMap<>();
        map.put("topic", invitataionEntity);
        map.put("user", userEntity);
        map.put("commentVoList", commentEntityList);
        // 5.跳转到视图
        outView("view/site/discuss-detail", map);
    }
}
